# -*- coding: utf-8 -*-
from decimal import Decimal
import logging

from api.account.handler import get_fixed_num
from api.coupon import handler as coupon_handler

from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError

from django.views.decorators.http import require_GET, require_POST

from future.utils import raise_with_traceback

_LOGGER = logging.getLogger('bigbang')


@require_GET
@response_wrapper
@token_required
def get_my_coupons(request):
    """
    查看我的红包
    """
    try:
        page = int(request.GET.get('page', 0))
        size = int(request.GET.get('size', 0))
        status = int(request.GET['status']) if request.GET.get('status') else None
    except Exception as e:
        raise_with_traceback(ParamError(e))

    c_list, count = coupon_handler.view_user_coupons(request.user_id, status, page, size)
    data = {
        'list': c_list,
        'total_count': count
    }
    return data


@require_GET
@response_wrapper
# @token_required
def get_fresh_coupons(request):
    """
    查看我的新手红包
    """
    user_id = request.GET.get('user_id', 0)
    if not user_id:
        default_temps = coupon_handler.get_fresh_coupons_temp()
        return {'list': default_temps}
    c_list = coupon_handler.view_user_fresh_coupons(int(user_id))
    data = {
        'list': c_list,
    }
    return data


@require_GET
@response_wrapper
@token_required
def get_available_coupons(request):
    """
    获取可用红包
    """
    try:
        price = Decimal(request.GET['price'])
        activity_type = request.GET.get('activity_type')
        activity_type = int(activity_type)
        bet_type = request.GET.get('bet_type', 0)
        bet_type = int(bet_type)
    except Exception as e:
        raise_with_traceback(ParamError(e))

    a_list = coupon_handler.view_available_coupons(request.user_id, price, activity_type, bet_type)
    data = {
        'list': a_list,
        'total_count': len(a_list)
    }
    return data


@require_GET
@response_wrapper
@token_required
def get_recommend_coupon(request):
    """
    支付时获取一个推荐使用的红包
    """
    try:
        price = Decimal(request.GET['price'])
        activity_type = request.GET.get('activity_type')
        activity_type = int(activity_type)
        bet_type = request.GET.get('bet_type', 0)
        bet_type = int(bet_type)
    except Exception as e:
        raise_with_traceback(ParamError(e))

    recommend_coupon = coupon_handler.get_recommend_coupon(request.user_id, price, activity_type, bet_type)
    return recommend_coupon
